package com.action.impl;

import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.struts2.ServletActionContext;
import org.json.JSONException;
import org.json.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
import com.utils.HttpPostUtil;
import com.utils.LoaderFileUtil;

public class TaobaoAction extends ActionSupport{
	public String oauth2() {
		String code=ServletActionContext.getRequest().getParameter("code");
		List <NameValuePair> params = LoaderFileUtil.loadTBOauth("taobao_app.properties");  		
	    params.add(new BasicNameValuePair("code", code));   
	    String uri = "https://oauth.taobao.com/token";
	    String accessToken = null;
	    String nick = null;
	    String result = HttpPostUtil.doPost(uri, params);
	    if(result!=null){
	    	try {
				JSONObject jsonObj = new JSONObject(result);
				accessToken = jsonObj.getString("access_token");
				nick = jsonObj.getString("taobao_user_nick");
				System.out.println("AccessToken: " + accessToken);
				System.out.println("nick: " + nick);
			} catch (JSONException e) {
				return "error";
			}
	    }
	    return SUCCESS;
	}

	public void oauth1() throws IOException {
		Properties props=LoaderFileUtil.readTBOauth("taobao_app.properties");
		String TBOauthUrl="https://oauth.taobao.com/authorize?client_id="+props.get("client_id")+"&view=web&response_type=code&scope=item&redirect_uri="
				+props.getProperty("redirect_uri");
		ServletActionContext.getResponse().getWriter().write(TBOauthUrl);
	}
}
